<template>
  <div class="equipment-inspection">
    <div class="header">
      <div class="controls">
        <el-button 
          type="primary" 
          icon="el-icon-check" 
          :disabled="selectedDevices.length === 0"
          @click="batchInspection"
          size="large"
        >
          批量点检
        </el-button>
      </div>
      <h1>设备点检管理</h1>
    </div>
    
    <div class="table-container split-view">
      <div class="table-column">
        <el-table 
          :data="leftDeviceList" 
          style="width: 100%" 
          height="calc(100vh - 120px)"
          @selection-change="handleSelectionChange"
          stripe
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
        >
          <el-table-column type="selection" width="55" fixed />
          <el-table-column prop="name" label="设备名称" :width="getColumnWidth(100)" fixed />
          <el-table-column prop="status" label="设备状态" :width="getColumnWidth(100)">
            <template #default="{row}">
              <el-tag :type="statusTagType(row.status)" :effect="'dark'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="line" label="线体" :width="getColumnWidth(100)" />
          <el-table-column prop="type" label="设备类型" :width="getColumnWidth(130)" />
          <el-table-column prop="inspectionStatus" label="点检情况" :width="getColumnWidth(120)">
            <template #default="{row}">
              <el-tag :type="row.inspectionStatus === '已点检' ? 'success' : 'danger'" :effect="'dark'">
                {{ row.inspectionStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="getColumnWidth(200)" fixed="right">
            <template #default="{row}">
              <el-button 
                v-if="row.inspectionStatus === '未点检'"
                type="primary" 
                size="small" 
                @click="handleInspection(row)"
              >
                点检
              </el-button>
              <span v-else style="color: #999">--</span>
              <el-button 
                type="warning" 
                size="small" 
                style="margin-left: 5px"
                @click="handleMaintenance(row)"
              >
                维保
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="table-column">
        <el-table 
          :data="rightDeviceList" 
          style="width: 100%" 
          height="calc(100vh - 120px)"
          @selection-change="handleSelectionChange"
          stripe
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
        >
          <el-table-column type="selection" width="55" fixed />
          <el-table-column prop="name" label="设备名称" :width="getColumnWidth(100)" fixed />
          <el-table-column prop="status" label="设备状态" :width="getColumnWidth(100)">
            <template #default="{row}">
              <el-tag :type="statusTagType(row.status)" :effect="'dark'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="line" label="线体" :width="getColumnWidth(100)" />
          <el-table-column prop="type" label="设备类型" :width="getColumnWidth(130)" />
          <el-table-column prop="inspectionStatus" label="点检情况" :width="getColumnWidth(120)">
            <template #default="{row}">
              <el-tag :type="row.inspectionStatus === '已点检' ? 'success' : 'danger'" :effect="'dark'">
                {{ row.inspectionStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="getColumnWidth(200)" fixed="right">
            <template #default="{row}">
              <el-button 
                v-if="row.inspectionStatus === '未点检'"
                type="primary" 
                size="small" 
                @click="handleInspection(row)"
              >
                点检
              </el-button>
              <span v-else style="color: #999">--</span>
              <el-button 
                type="warning" 
                size="small" 
                style="margin-left: 5px"
                @click="handleMaintenance(row)"
              >
                维保
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 维保对话框 -->
    <el-dialog
      v-model="maintenanceDialogVisible"
      title="设备维保申请"
      :width="'500px'"
      :before-close="handleDialogClose"
    >
      <el-form :model="maintenanceForm" ref="maintenanceForm" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="maintenanceForm.deviceName" disabled />
        </el-form-item>
        <el-form-item 
          label="请求描述" 
          prop="description"
          :rules="[
            { required: true, message: '请输入维保请求描述', trigger: 'blur' },
            { min: 5, message: '描述至少5个字符', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="maintenanceForm.description"
            type="textarea"
            :rows="5"
            placeholder="请详细描述设备需要维保的问题..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitMaintenance">提交维保申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'EquipmentInspection',
  data() {
    return {
      selectAll: false,
      selectedDevices: [],
      deviceList: [],
      all_info_devices: [],
      windowWidth: window.innerWidth,
      // 维保相关变量
      maintenanceDialogVisible: false,
      maintenanceForm: {
        deviceName: '',
        description: '',
        deviceId: null
      }
    };
  },
  mounted() {
    this.get_dj_info();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  computed: {
    // 计算左侧表格的设备列表
    leftDeviceList() {
      if (this.deviceList.length === 0) return [];
      const middle = Math.ceil(this.deviceList.length / 2);
      return this.deviceList.slice(0, middle);
    },
    // 计算右侧表格的设备列表
    rightDeviceList() {
      if (this.deviceList.length === 0) return [];
      const middle = Math.ceil(this.deviceList.length / 2);
      return this.deviceList.slice(middle);
    }
  },
  methods: {
    get_dj_info() {
      console.log("KKK");
      const loadingInstance = this.$loading({
        lock: true,
        text: '同步MES数据中···', 
        spinner: 'el-icon-loading',
        background: 'rgba(247, 237, 237, 0.7)'
      });
      
      const longTimeoutAxios = axios.create({
        timeout: 600000 // 独立实例默认值
      });
      
      var ccdstatus = {"run":"运行","fault":"故障","waiting":"待机","no":"未排产","other":"其他"};
      
      longTimeoutAxios.get('api/daojiaoGD/shebei_db_for_dj')
        .then((reslut) => {
          loadingInstance.close();
          console.log(reslut.data);
          var all_devices_info = reslut.data;
          this.all_info_devices = reslut.data;
          
          this.deviceList = all_devices_info.map((item, index) => {
            var dianjian_ = "未点检";
            if(item.dj != ""){
              dianjian_ = item.dj;
            }
            return {
              id: index + 1,
              name: item.name,
              status: ccdstatus[item.ccd_status],
              line: item.xianti_numb + "#线",
              type: item.category_id,
              inspectionStatus: dianjian_,
              lastInspection: item.lastInspection || ''
            };
          });
        })
        .catch((error) => {
          console.log("失败", error);
          loadingInstance.close();                            
        });
    },
    statusTagType(status) {
      const map = {
        '运行': 'success',
        '待机': 'warning',
        '维护': 'info',
        '故障': 'danger'
      };
      return map[status] || 'info';
    },
    handleResize() {
      this.windowWidth = window.innerWidth;
    },
    getColumnWidth(baseWidth) {
      // 计算基础缩放比例，基于1920px的设计宽度
      const baseWidthDesign = 1920;
      const scale = Math.min(Math.max(this.windowWidth / baseWidthDesign, 0.7), 1.3);
      
      // 计算最终宽度，最小不小于基础宽度的70%，最大不超过130%
      return Math.round(baseWidth * scale);
    },
    handleSelectionChange(selection) {
      this.selectedDevices = selection;
      this.selectAll = selection.length === this.deviceList.length && this.deviceList.length > 0;
    },
    handleInspection(device) {
        //单个设备点检
        console.log(device,"?????????")
        console.log(this.all_info_devices,"lllllllll")
        // var mesid_ = 0
        for(let i=0;i<this.all_info_devices.length;i++){
            if(this.all_info_devices[i].name == device.name){
                // 放接口
                var mesid_ = this.all_info_devices[i].mesid
                var shebei_type_ = this.all_info_devices[i].category_id
                let mes_data_final = []
                let mes_data = {  
                  shebei_type: shebei_type_, 
                  mesid: mesid_,
                }
                mes_data_final.push(mes_data)
                let jsonString_mes_data = JSON.stringify(mes_data_final)
                
                console.log("KKK",mesid_,this.all_info_devices[i].category_id)
                const loadingInstance = this.$loading({
                    lock: true,
                    text: '设备正在点检···', 
                    spinner: 'el-icon-loading',
                    background: 'rgba(247, 237, 237, 0.7)'
                });                
                this.http.get('api/daojiaoGD/dianjian_devices',
                    {mes_data:jsonString_mes_data})
                    .then((reslut) => {
                    loadingInstance.close(); 
                    if(reslut == "成功"){
                        device.inspectionStatus = '已点检';
                        device.lastInspection = this.getCurrentTime();
                        this.$message.success(`设备 ${device.name} 点检完成`);
                    }
                    })
                    .catch((error) => {
                    console.log("失败", error);
                    loadingInstance.close();                            
                    });
            }
        }      
    },
    batchInspection() {
        //批量点检
      const uncheckedDevices = this.selectedDevices.filter(d => d.inspectionStatus === '未点检');
      console.log(uncheckedDevices,"批量点检·····")
      
      if (uncheckedDevices.length === 0) {
        this.$message.warning('选中的设备都已点检');
        return;
      }
      
      const currentTime = this.getCurrentTime();
      uncheckedDevices.forEach(device => {
        device.inspectionStatus = '已点检';
        device.lastInspection = currentTime;
      });
      
      this.$message.success(`成功点检 ${uncheckedDevices.length} 台设备`);
      this.selectedDevices = [];
      this.selectAll = false;
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    },
    // 维保相关方法
    handleMaintenance(row) {
      // 打开维保对话框并初始化数据
      this.maintenanceDialogVisible = true;
      this.maintenanceForm = {
        deviceName: row.name,
        description: '',
        deviceId: row.id
      };
      // 重置表单验证
      this.$nextTick(() => {
        this.$refs.maintenanceForm.resetFields();
      });
    },
    handleDialogClose() {
      this.maintenanceDialogVisible = false;
      this.$refs.maintenanceForm.resetFields();
    },
    submitMaintenance() {
      this.$refs.maintenanceForm.validate((valid) => {
        if (valid) {
          // 模拟提交维保申请
          console.log('提交维保申请:', this.maintenanceForm.description);
          for(let i=0;i<this.all_info_devices.length;i++){
            if(this.all_info_devices[i].name == this.maintenanceForm.deviceName){
                // 放接口
                var mesid_ = this.all_info_devices[i].mesid
                var shebei_type_ = this.all_info_devices[i].category_id
                let mes_data_final = []
                let mes_data = {  
                  shebei_type: shebei_type_, 
                  mesid: mesid_,
                  wb_name:this.maintenanceForm.description
                }
                mes_data_final.push(mes_data)
                let jsonString_mes_data = JSON.stringify(mes_data_final)
                
                console.log("KKK",mesid_,this.all_info_devices[i].category_id,jsonString_mes_data)
                const loadingInstance = this.$loading({
                    lock: true,
                    text: '提交维保申请中...', 
                    spinner: 'el-icon-loading',
                    background: 'rgba(247, 237, 237, 0.7)'
                });                
                this.http.get('api/daojiaoGD/wb_devices',
                    {mes_data:jsonString_mes_data})
                    .then((reslut) => {
                    loadingInstance.close(); 
                    if(reslut == "成功"){
                        this.$message.success('维保申请已提交，将尽快处理');
                        this.maintenanceDialogVisible = false;
                        this.$refs.maintenanceForm.resetFields();
                    }
                    })
                    .catch((error) => {
                    console.log("失败", error);
                    loadingInstance.close();                            
                    });
            }
          }    
        }
      });
    }
  }
};
</script>

<style scoped>
.equipment-inspection {
  padding: clamp(10px, 1vw, 15px);
  height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
}

.header {
  background: linear-gradient(135deg, #409EFF, #337ecc);
  color: white;
  padding: clamp(10px, 1vw, 15px) clamp(15px, 1.5vw, 20px);
  border-radius: 8px;
  margin-bottom: clamp(10px, 1vw, 15px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0;
  font-size: clamp(20px, 2vw, 28px);
  font-weight: 600;
}

.controls {
  display: flex;
  align-items: center;
}

.split-view {
  display: flex;
  gap: clamp(10px, 1vw, 15px);
}

.table-column {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.el-table {
  border-radius: 8px;
  font-size: clamp(14px, 1vw, 16px);
}

.el-table::before {
  height: 0;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #e6f7ff !important;
}

.el-table th {
  background-color: #f0f2f5;
  color: #1890ff;
  font-weight: 600;
  font-size: clamp(14px, 1vw, 16px);
}

.el-table__fixed-right::before, .el-table__fixed::before {
  height: 0;
}

.el-tag {
  font-weight: 500;
  padding: clamp(3px, 0.3vw, 4px) clamp(6px, 0.5vw, 8px);
  font-size: clamp(12px, 0.8vw, 14px);
}

.el-button {
  font-size: clamp(14px, 1vw, 16px);
}

/* 调整操作列宽度以适应两个按钮 */
.el-table-column--fixed-right {
  padding-right: 10px !important;
}
</style>